﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Navigation;
using Fayshine.VA.Helpers;
using Fayshine.VA.Models;
using Fayshine.VA.RIAService.Web;
using Fayshine.VA.ViewModels;
using Visifire.Charts;
using LocalBusyIndicator = Fayshine.VA.Controls.BusyIndicator;

namespace Fayshine.VA.Views.SearchStatistics
{
    public partial class AverageStranded : Page
    {
        private DateTime m_StartDate;
        private DateTime m_EndDate;
        private SearchStatisticsViewModel m_ViewModel;
        public AverageStranded()
        {
            InitializeComponent();
            this.Loaded += new RoutedEventHandler(AverageStranded_Loaded);
          
        }

        void AverageStranded_Loaded(object sender, RoutedEventArgs e)
        {
            LocalBusyIndicator indicator = Application.Current.RootVisual as LocalBusyIndicator;
            indicator.IsBusy = true;

            this.startDatePicker.SelectedDate = DateTime.Now;
            this.endDatePicker.SelectedDate = DateTime.Now;

            m_ViewModel = new SearchStatisticsViewModel();
            m_ViewModel.AppendHistoryPassengerFlow += new AppendHistoryPassengerFlowEventHandler(m_ViewModel_AppendHistoryPassengerFlow);
            m_ViewModel.ResetHisotryChartEvent += new ResetHistoryChartEventHandler(m_ViewModel_ResetHisotryChartEvent);
            this.DataContext = m_ViewModel;

            m_ViewModel.GetAllAreas();
        }

        private void m_ViewModel_ResetHisotryChartEvent()
        {
            this.Dispatcher.BeginInvoke(delegate()
            {
                if (vcChart1 != null)
                {
                    vcChart1.AxesX.Clear();
                    vcChart1.TrendLines.Clear();
                    vcChart1.Series.Clear();
                    vcChart1.Titles.Clear();
                    vcChart1.AxesY.Clear();
                }
            });
        }

        private void m_ViewModel_AppendHistoryPassengerFlow(string title, bool isIn, List<HistoryPassengerFlow> firstHistoryPassengerFlow, List<HistoryPassengerFlow> secondHistoryPassengerFlow)
        {
            this.Dispatcher.BeginInvoke(delegate()
            {

                HistoryPassengerFlow allCountSource = firstHistoryPassengerFlow[firstHistoryPassengerFlow.Count - 1];
                List<HistoryPassengerFlow> source = firstHistoryPassengerFlow;
                firstHistoryPassengerFlow.RemoveAt(firstHistoryPassengerFlow.Count - 1);

                Title vcChart1Title = new Visifire.Charts.Title();
                vcChart1Title.Text = GetTitleForDate();
                vcChart1.Titles.Add(vcChart1Title);


                TrendLine minLine = new TrendLine();
                minLine.Value = firstHistoryPassengerFlow.Min(f => f.StrandedMinutes);
                minLine.LabelText = "最小:" + minLine.Value.ToString();
                minLine.FlowDirection = System.Windows.FlowDirection.LeftToRight;
                vcChart1.TrendLines.Add(minLine);

                DataSeries series = ChartHelper.GetDataSeries(RenderAs.Line, "平均滞留时间（分钟）", ChartValueTypes.Auto);
                series.DataMappings.Add(ChartHelper.GetDataMapping("AxisXLabel", "DisplayTitle"));
                series.DataMappings.Add(ChartHelper.GetDataMapping("YValue", "StrandedMinutes"));
                series.DataSource = firstHistoryPassengerFlow;
                vcChart1.Series.Add(series);

                firstHistoryPassengerFlow.Add(allCountSource);
                this.dataGrid.ItemsSource = firstHistoryPassengerFlow;

                LocalBusyIndicator indicator = Application.Current.RootVisual as LocalBusyIndicator;
                indicator.IsBusy = false;
            });
        }

        private void cmbAreas_DropDownClosed(object sender, EventArgs e)
        {
            if (m_ViewModel != null)
            {
                List<area> selectedArea = new List<area>();
                var selectAreaExt = m_ViewModel.AreaExtends.Where(a => a.IsSelected).ToList();
                selectAreaExt.ForEach(b =>
                {
                    area temp = b.Tag as area;
                    selectedArea.Add(temp);
                });

                if (selectedArea.Count > 0)
                {
                    cbItemDisplay.Content = selectedArea.Count > 1 ? selectedArea[0].Name + "..." : selectedArea[0].Name;

                }
                else
                {
                    cbItemDisplay.Content = string.Empty;
                }
                cmbAreas.SelectedItem = null;
                cmbAreas.SelectedItem = cbItemDisplay;

                m_ViewModel.SelectAreasChanged(selectedArea);
            }
        }

        // Executes when the user navigates to this page.
        protected override void OnNavigatedTo(NavigationEventArgs e)
        {
        }

        private void btnSearch_Click(object sender, RoutedEventArgs e)
        {
            m_StartDate = new DateTime(startDatePicker.SelectedDate.Value.Year,
                                       startDatePicker.SelectedDate.Value.Month,
                                       startDatePicker.SelectedDate.Value.Day,
                                       0, 0, 0);
            m_EndDate = new DateTime(endDatePicker.SelectedDate.Value.Year,
                                     endDatePicker.SelectedDate.Value.Month,
                                     endDatePicker.SelectedDate.Value.Day,
                                     0, 0, 0);

            if (m_StartDate > m_EndDate)
            {
                MessageBox.Show("开始日期不能大于结束日期");
                return;
            }

            if (!m_ViewModel.IsConditionSelected())
            {
                MessageBox.Show("请选择店铺！");
                return;
            }
            else
            {
                LocalBusyIndicator indicator = Application.Current.RootVisual as LocalBusyIndicator;
                indicator.IsBusy = true;
                m_ViewModel.RefreshPassengerflowTimeStamp(true, m_StartDate, m_EndDate.AddDays(1));
            }

        }

        private string GetTitleForDate()
        {
            string title = string.Empty;
            if (startDatePicker.SelectedDate.Value.Date == endDatePicker.SelectedDate.Value.Date)
            {
                title = startDatePicker.SelectedDate.Value.ToShortDateString();
            }
            else
            {
                title = startDatePicker.SelectedDate.Value.ToShortDateString() + "至" + endDatePicker.SelectedDate.Value.ToShortDateString();
            }
            title = title + " 平均滞留时间分布图（";

            m_ViewModel.AreaExtends.each(a =>
            {

                if (a.IsSelected)
                {
                    title = title + "-" + a.Name + "-";
                }

            });
            title = title + ")";
            return title;
        }

        private void btnExport_Click(object sender, RoutedEventArgs e)
        {
            SaveFileDialog fsd = new SaveFileDialog();
            fsd.Filter = "PDF (*.pdf)|*.pdf|*PNG (*.png)|*.png";

            if (fsd.ShowDialog() == true)
            {
                LocalBusyIndicator indicator = Application.Current.RootVisual as LocalBusyIndicator;
                indicator.IsBusy = true;
                this.Dispatcher.BeginInvoke(delegate()
                {
                    FayshineManager.Instance.ExportToDisk(fsd, spContent);
                });
            }
        }

    }
}
